<template>
    <div>
        <el-row style="margin-bottom: 15px">
            <el-col span="2">
                <el-button @click="addPostBth()" style="height:60px; width:60px; border-radius: 50%; background-color: #42b983; border: #42b983;">
                    <i class="el-icon-edit" style="font-size: 28px; color: white;"></i>
                </el-button>
            </el-col>
            <el-col span="20">
            <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="🍅标题">
                <el-input v-model="searchObj.title" placeholder="帖子的标题" /> 
            </el-form-item>
            <el-form-item label="🥝内容">
                <el-input v-model="searchObj.text" placeholder="帖子的内容" /> 
            </el-form-item>
            <el-form-item label="🍇类别">
                <el-select v-model="searchObj.type" placeholder="请选择类型">
                    <el-option
                    v-for="type in typeList"
                    :key="type.id"
                    
                    :label="type.typeName"
                    :value="type.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <!--这个单选框↑，使用完v-for要空一行，要不的话会有红色的>，然后下面的代码都加粗了，不知道为什么-->
            <el-button type="primary" icon="el-icon-search" @click="getAllPost()">查询</el-button>
            <el-button type="default" @click="resetData()">清空</el-button>
            </el-form>
            </el-col>
        </el-row>
        <el-row>
            <el-col span="6" v-for="item in postList" :key="item.id" id="goodsCard">
            <el-card el-card :body-style="{ padding: '0px' }" style="margin: 5px; height: 440px;" shadow="hover">
                <div style="padding-left: 10px; padding-right: 20px; padding-top: 5px;">
                    <el-row>
                        <el-col span="3">
                            <div style="text-align: left;">
                                <el-avatar :src=getAvatarById(item.userId)></el-avatar>
                            </div>
                        </el-col>
                        <el-col span="12">
                            <div style="text-align: left; padding-top: 15px;">
                                {{getUserById(item.userId)}}
                            </div>
                        </el-col>                            
                        <el-col span="4">
                            <el-button v-if="!item.isLike" round @click="like(item.id)">(●TAT●){{ item.liked }}</el-button>
                            <el-button v-if="item.isLike"  round @click="like(item.id)">(●ˇ∀ˇ●){{ item.liked }}</el-button>
                        </el-col>
                    </el-row>  
                </div>
                <div @click="getDetails(item)">
                    <img :src="item.pic" class="image">
                    <div style="padding: 14px;">
                        <div style="margin-bottom: 10px; font-size: 16px; font-weight: bold; text-align: left;">
                            <el-tag effect="plain">{{getTypeById(item.type)}}</el-tag>
                            {{item.title}}
                        </div>                   
                    </div>
                </div>         
            </el-card>
            </el-col>
        </el-row>

        <!--页码-->
        <el-row style="margin-top: 20px;">
            <el-col :span="24"><el-pagination background layout="prev, pager, next" :page-size="limit" :total="total" :current-page="page" @current-change="changeCurrentPage"></el-pagination></el-col>
        </el-row>
        
        
        <el-dialog
        :visible.sync="dialogVisible"
        width="800px"
        :before-close="handleClose">
        <el-row>
            <el-col span="11">
                <img :src="postInfo.pic" class="image">
            </el-col>
            <el-col span="12" offset="1">
                <div class="infinite-list-wrapper" style="overflow: auto; height: 324px;">
                    <ul>
                    <!-- 第一条数据来自指定数据 -->
                    <li>
                        <div style="margin-bottom: 16px; font-size: 16px; font-weight: bold; text-align: left;">{{postInfo.title}}</div>
                        <div style="margin-bottom: 8px; text-align: left;">{{postInfo.text}}</div>
                        <div style="margin-bottom: 8px; text-align: left;">
                            <el-tag effect="plain" style="margin-right: 10px;">{{getTypeById(postInfo.type)}}</el-tag>
                            <el-button v-if="!postInfo.isLike" round @click="like(postInfo.id)">❤{{ postInfo.liked }}</el-button>
                            <el-button v-if="postInfo.isLike" type="danger" round @click="like(postInfo.id)">❤{{ postInfo.liked }}</el-button>
                        </div>
                        <div style="margin-bottom: 2px; text-align: left;">{{postInfo.createTime}}</div>
                        <hr>
                        <el-row>
                            <el-col :span="19"><el-input v-model="comment" placeholder="我也来说两句~"></el-input></el-col>
                            <el-col :span="5"><el-button type="primary" @click="sendComment(postInfo.id)">发送</el-button></el-col>
                        </el-row>
                    </li>
                    <!-- 其他项来自另一个列表 -->
                    <li v-for="(comment, index) in commentList" :key="index" class="list-item">
                        <div style="text-align: left;">
                        <strong>{{ comment.userName }}</strong>: {{ comment.comment }}({{ comment.createTime }})
                        </div>
                    </li>
                    </ul>
                    <p>没有更多了</p>
                </div>
            </el-col>
        </el-row>
        <span slot="footer">
            <el-avatar :src="userInfo.avatar"></el-avatar>
            {{getUserById(userInfo.id)}}
        <el-button v-if="!isFollow" round type="primary" @click="toFollow(userInfo.id, isFollow)">关注</el-button>
        <el-button v-if="isFollow"  round type="primary" @click="toFollow(userInfo.id, isFollow)">取消关注</el-button>
        </span>
        </el-dialog>

        <el-drawer
        title="发表"
        :visible.sync="drawer"
        with-header=true
        :before-close="handleClose">
        <div style="padding:30px">
            <el-form ref="saveObj" :model="form" label-width="60px">
                <el-form-item label="标题">
                    <el-input v-model="saveObj.title"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <el-upload class="avatar-uploader"
                            action= "http://localhost:8333/post/postInfo/upload"
                            :show-file-list="false"
                            :on-success="handleSuccess"
                            ref="upload">
                        <img v-if="img" :src="img" class="image"/>
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="内容">
                    <el-input type="textarea" :rows="3" v-model="saveObj.text"></el-input>
                </el-form-item>
                <el-form-item label="类别">
                    <el-select v-model="saveObj.type" placeholder="请选择类别">
                        <el-option
                        v-for="type in typeList"
                        :key="type.id"

                        :label="type.typeName"
                        :value="type.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <div style="margin-top: 10px;">
                    <el-button type="primary" @click="onSubmitWithSave">完成</el-button>
                </div>                    
            </el-form>
        </div>
        </el-drawer>
    </div>
</template>

<script>

import PostInfoApi from '../../api/post/postInfo'
import PostTypeApi from '../../api/post/postType'
import UserInfoApi from '../../api/mime/userinfo'
import UserFollowApi from '../../api/mime/userFollow'
import PostCommentApi from '../../api/post/postComment'

export default {
    data() {
        return {
            postList: [],
            typeList: [],
            userList: [],
            commentList: [],
            comment:'',
            typeId: '',
            userInfo: {},
            postInfo: {},
            dialogVisible: false,
            isFollow: false,
            saveObj: {},
            drawer: false,
            searchObj: {},
            total: 0, // 总记录数
            page: 1, // 页码
            limit: 8, // 每页记录数
            headers: { Authorization: localStorage.getItem('authorization') },
            img:'',
        }
    },
    methods: {
        handleSuccess (response, file, fileList) {
            console.log(response)
              this.saveObj.pic = `http://localhost:8333/post/postInfo/download?name=${response.data}`
              this.img = this.saveObj.pic
              console.log(this.saveObj.pic)
          },
        changeCurrentPage(page) {
            this.page = page
            this.getAllPost()
        },
        onSubmitWithSave() {
            this.$confirm('你确定要发表帖子吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                return PostInfoApi.addPost(this.saveObj)
            }).then((res) => {
                if (res.data.code == 200) {
                    this.$message.success(res.data.message)
                    this.getAllPost()
                    this.drawer = false
                    this.saveObj = {}
                    this.img = ''
                } else {
                    this.$message.error(res.data.message);
                }
            }).catch(err => {
                if (err === 'cancel') {
                    this.$message.info('取消添加')
                } else {
                    this.$message.warning("请先登录哦 /(*≧︶≦))(￣▽￣* )ゞ")
                }
            })
        },
        handleCloseWithAdd(done) {
            this.$confirm('确定退出发布信息？')
                .then(_ => {
                    done(); //不清空
                })
                .catch(_ => {});
        },
        addPostBth() {
            this.drawer = true;
        },
        //关注
        toFollow(userId, isFollow) {
            UserFollowApi.toFollow(userId, isFollow)
            .then(res => {
                if (res.data.code == 200) {
                    this.getisFollow(userId);
                    this.$message.success(res.data.message);
                }else {
                    this.$message.error(res.data.message);
                }
            }).catch(res => {
                this.$message.warning("请先登录哦 /(*≧︶≦))(￣▽￣* )ゞ")                
            })
        },
        //查看是否关注
        getisFollow(id) {
            UserFollowApi.isFollow(id)
            .then(res => {
                this.isFollow = res.data.data
                console.log("是否关注了这个人？"+ this.isFollow)
            })
        },
        //发送评论
        sendComment(id) {
            PostCommentApi.sendComment(id, this.comment)
            .then(res => {
                this.comment = ''
                this.getComment(id)
            })
        },
        //获取详情
        getDetails(item) {
            this.dialogVisible = true
            this.comment = ''
            this.getUserInfo(item.userId)
            this.getPostInfo(item.id)
            this.getisFollow(item.userId)
            this.getComment(item.id)
        },
        handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
        },
        //获取用户信息
        getUserInfo(id) {
            UserInfoApi.getUserById(id)
            .then(res => {
                this.userInfo = res.data.data
            })
        },
        //获取评论
        getComment(id) {
            PostCommentApi.getCommentById(id)
            .then(res => {
                this.commentList = res.data.data
            })
        },
        //获取帖子信息
        getPostInfo(id) {
            PostInfoApi.getPostById(id)
            .then(res => {
                this.postInfo = res.data.data
            })
        },
        //点赞
        like(id) {
            PostInfoApi.like(id)
            .then(res => {
                if (res.data.code == 200) {
                    this.$message.success(res.data.message);
                    this.getPostInfo(id)
                    this.getAllPost()
                } else {
                    this.$message.error(res.data.message);
                }
            }).catch(res => {
                this.$message.warning("请先登录哦 /(*≧︶≦))(￣▽￣* )ゞ")                
            })
        },
        getAllPost() {
            PostInfoApi.pageListWithLike(this.page, this.limit, this.searchObj)
            .then(res => {
                this.postList = res.data.data.records
                this.total = res.data.data.total
            })
        },
        getAllType() {
            PostTypeApi.getAllType()
            .then(res => {
                this.typeList = res.data.data
                console.log(res)
            })
        }, 
        getAllUser() {
            UserInfoApi.getAllUser()
            .then(res => {
                this.userList = res.data.data
                console.log(res)
            })
        },
        resetData() {
            this.searchObj = {}
            this.getAllPost()
        },
    },
    created() {
        this.drawer = false
        this.getAllType()
        this.getAllUser()
        // this.getAllPost()
    },
    computed: {
        //跟据id获取flower
        getUserById() {
            return id => {
                const item = this.userList.find(item => item.id == id)
                return item ? item.nickName : ''
            }
        },
        getAvatarById() {
            return id => {
                const item = this.userList.find(item => item.id == id)
                console.log(item)
                return item ? item.avatar : ''
            }
        },
        getTypeById() {
            return id => {
                const item = this.typeList.find(item => item.id == id)
                return item ? item.typeName : ''
            }
        },
    },
    mounted() {
        // 获取路由参数
        const type = this.$route.params.type;
        this.searchObj.type = type;
        this.getAllPost()
    },
}
</script>

<style scoped>
.image{
    width: 100%;
    height: 324px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  ul {
    list-style-type: none; /* 移除无序列表的默认样式 */
    padding: 0; /* 可选：移除列表的内边距 */
  }
</style>
